<template>
	<z-paging ref="paging" v-model="dataList" @query="queryList"
		:loading-more-custom-style="{ paddingBottom: 'env(safe-area-inset-bottom)' }">
		<template #top>
			<view class="zpagin_top">
				<nav-bar :iconLeft="true" />
				<view class="search">
					<custom-search v-model="queryParams.search" @search="refreshList" placeholder="请输入计量单位名称" />
				</view>
				<dui-float-ball @touchFunc="touchFunc" v-if="$hasPerm(['20401'])" />
			</view>
		</template>
		<up-swipe-action>
			<up-swipe-action-item v-for="item in dataList" :key="item.id"
				:name="JSON.stringify(swipeActPer(options, null)) + '&' + item.id + '&' + item.name"
				:options="swipeActPer(options, null)" :disabled="swipeActPer(options, null, 'disabled')" @click="action">
				<uni-card margin="0" spacing="0">
					<template v-slot:title>
						<uni-list>
							<uni-list-item :title="item.name" :note="item.code">
								<template v-slot:footer>
									<view style="display: flex; align-items: center;">
										<up-tag size="mini" :text="status_list[item.if_open].text" plain plainFill
											:type="status_list[item.if_open].type" style="display: inline-block;" />
										<switch style="transform:scale(0.7)" :checked="Boolean(item.if_open)"
											@change="checkedChange($event, item.id)" v-if="$hasPerm(['20406'])" />
									</view>
								</template>
							</uni-list-item>
						</uni-list>
					</template>
					<view class="ctent">仓库类型：{{ item.classify_display }}</view>
					<view class="con">
						<view class="ctent">面积(㎡)：{{ item.area }}</view>
						<view class="ctent">管理员：{{ item.user_full_names }}</view>
					</view>
					<view class="con" style="align-items: normal;">
						<view class="ctent" style="flex: none;">地址：</view>
						<view class="ctent">{{ item.address }}</view>
					</view>
					<view>添加时间：{{ item.create_date }}</view>
					<view class="con" style="align-items: normal;">
						<view class="ctent" style="flex: none;">备注：</view>
						<view class="ctent">{{ item.desc }}</view>
					</view>
				</uni-card>
			</up-swipe-action-item>
		</up-swipe-action>
		<template #bottom>
			<custom-popup :popupShow="popupShow" mode="center" :title="titlePop" width="96%" :closeable="false"
				:closeOnClickOverlay="false">
				<view style="background-color: #fff; padding: 20rpx 30rpx;">
					<uni-forms labelPosition="left" :model="form" :rules="rules" ref="refForm" labelWidth="100px">
						<uni-forms-item label="仓库编号" name="code" required>
							<view style="display: flex;gap:20rpx">
								<uni-easyinput v-model="form.code" placeholder="请输入编号" class="iptBor" :inputBorder="false"
									:disabled="switchCode" />
								<view style="margin-left: 20rpx" v-show="titlePop == '新增'">
									<u-switch v-model="switchCode" @change="switchChange" size="20" />
									自动生成
								</view>
							</view>
						</uni-forms-item>
						<uni-forms-item label="仓库类型" name="classify" required>
							<uni-data-select v-model="form.classify" :localdata="classify_list" placeholder="请选择仓库类型"
								mode="underline" />
						</uni-forms-item>
						<uni-forms-item label="仓库名称" name="name" required>
							<uni-easyinput v-model="form.name" placeholder="请输入仓库名称" class="iptBor" :inputBorder="false" />
						</uni-forms-item>
						<uni-forms-item label="面积(㎡)" name="area" required>
							<uni-easyinput v-model="form.area" type="number" placeholder="请输入面积(㎡)" class="iptBor"
								:inputBorder="false" />
						</uni-forms-item>
						<uni-forms-item label="地址" name="address" required>
							<uni-easyinput v-model="form.address" placeholder="请输入地址" class="iptBor" :inputBorder="false" />
						</uni-forms-item>
						<uni-forms-item label="仓管员">
							<uni-data-select v-model="form.user_full_list" :localdata="account_list" placeholder="请选择仓管员"
								mode="underline" multiple />
						</uni-forms-item>
						<uni-forms-item label="备注">
							<uni-easyinput type="textarea" v-model="form.desc" placeholder="请输入备注" />
						</uni-forms-item>
					</uni-forms>
					<view class="btn-box">
						<u-button text="取 消" @click="cancal"></u-button>
						<u-button type="primary" text="提 交" @click="save"></u-button>
					</view>
				</view>
			</custom-popup>
		</template>
	</z-paging>
</template>
<script setup>
import { ref, reactive } from 'vue'
import { onLoad } from '@dcloudio/uni-app'
import daWarehouseApi from '../../../api/dataa/da_warehouse'
import { swipeActPer } from '@/utils/permission' // 用防抖优化请求频率（下面给出）
import { generateCode } from '@/utils/index.js';

onLoad(() => {
	get_account_list()
})
//自动生成按钮
const switchCode = ref(true);
function switchChange(v) {
	if (v) {
		form.code = generateCode('WA')
	}
};
//tag标签状态
const status_list = {
	0: { text: '禁用', type: 'error' },
	1: { text: '启用', type: 'success' }
}
const options = [
	{
		text: '修改', per: '20402',
		style: {
			backgroundColor: '#0081ff'
		}
	}, {
		text: '删除', per: '20403',
		style: {
			backgroundColor: '#f56c6c'
		}
	}
];

const classify_list = [
	{ text: '成品仓', value: 1 },
	{ text: '物料仓', value: 2 },
	{ text: '半成品仓', value: 3 },
	{ text: '五金仓', value: 4 },
	{ text: '不良品仓', value: 5 },
	{ text: '废品仓', value: 6 },
]

const queryParams = reactive({
	search: '',
});
const paging = ref(null);
const dataList = ref([]);
function queryList(pageNo, pageSize) {
	const params = {
		page: pageNo,
		page_size: pageSize,
		...queryParams
	}
	daWarehouseApi.get_warehouse(params).then((res) => {
		paging.value.complete(res.results);
	})
};

//switch操作
function checkedChange(e, id) {
	const if_open = e.detail.value ? 1 : 0
	daWarehouseApi.patch_warehouse({ if_open }, id).then(res => {
		uni.$u.toast(if_open ? '启用成功' : '禁用成功')
		setTimeout(() => {
			refreshList();
		}, 500)
	})
};


const refForm = ref(null);
const form = reactive({
	id: null,
	code: '',
	classify: '',
	name: '',
	area: '',
	address: '',
	user_full_list: '',
	desc: '',
});
const fields = Object.keys(form);
const rules = {
	code: { rules: [{ required: true, errorMessage: '请输入仓库编码' }] },
	name: { rules: [{ required: true, errorMessage: '请输入计量单位名称' }] },
	classify: { rules: [{ required: true, errorMessage: '请选择仓库类型' }] },
	area: { rules: [{ required: true, errorMessage: '请输入面积' }, { validateFunction: positiveNum }] },
	address: { rules: [{ required: true, errorMessage: '请输入仓库地址' }] },
};

//表单校验，
function positiveNum(rule, value, data, callback) {
	const num = /^([1-9]\d*|0)(\.\d{1,2})?$/.test(value);
	if (!num) callback('请输入正数，且最多保留两位小数');
	return true
}
const titlePop = ref('仓库弹窗')
const popupShow = ref(false)
function touchFunc() {
	titlePop.value = '新增'
	form.code = generateCode('WA')
	popupShow.value = true
}
//滑动操作按钮
function action(v) {
	const options = JSON.parse(v.name.split("&")[0])
	const id = v.name.split("&")[1]
	const delName = v.name.split("&")[2]
	const index = v.index
	if (options[index].text == '修改') {
		titlePop.value = '修改'
		get_detail(id)
	}
	if (options[index].text == '删除') {
		delete_type(id, delName)
	}
};

function get_detail(id) {
	daWarehouseApi.warehouse_detail(id).then(res => {
		const record = uni.$lodash.pick(res, fields)
		record.user_full_list = res.user_ids.split(',').map(v => Number(v))
		console.log(record)
		Object.assign(form, record)
		popupShow.value = true
	})
}

function save() {
	refForm.value.validate().then(() => {
		const params = uni.$lodash.cloneDeep(form) // 深拷贝一份form表单
		const selectedUsers = params.user_full_list.map(id =>
			account_list.value.find(user => user.value === id)
		).filter(Boolean)
		params.user_ids = selectedUsers.map(user => user.id).join(',')
		params.user_full_names = selectedUsers.map(user => user.text).join(',')
		delete params.user_full_list
		if (titlePop.value == '新增') {
			daWarehouseApi.post_warehouse(params).then(res => {
				uni.$u.toast('添加成功')
				setTimeout(() => {
					cancal()
					refreshList()
				}, 500)
			})
		} else {
			//修改
			daWarehouseApi.patch_warehouse(params, params.id).then((res) => {
				uni.$u.toast('修改成功')
				setTimeout(() => {
					cancal()
					refreshList();
				}, 500)
			})
		}
	}).catch((error) => {
		uni.$u.toast(error[0].errorMessage);
	})
};

function cancal() {
	popupShow.value = false
	Object.assign(form, {
		id: null,
		name: '',
		desc: '',
	})
}


//人员列表
const account_list = ref([])
function get_account_list() {
	daWarehouseApi.get_staff({ page: 1, page_size: 99999 }).then(res => {
		account_list.value = res.results.map(v => ({
			text: v.full_name,
			value: v.id
		}))
	})
};


//删除操作
function delete_type(id, delName) {
	uni.showModal({
		title: '提示',
		content: `确认要删除：【${delName}】的单位吗？`,
		success: (res) => {
			if (res.confirm) {
				daWarehouseApi.delete_warehouse(id).then((res) => {
					uni.$u.toast('删除成功')
					setTimeout(() => {
						refreshList();
					}, 500)
				})
			}
		}
	});
};

//编辑跳转刷新
function refreshList() {
	paging.value.reload();
};
</script>

<style lang="scss"></style>